package com.zjcode.cdcer.service.impl;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.RecursiveListUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.cdcer.mapper.TkmSysOrgMapper;
import com.zjcode.cdcer.mapper.TkmSysUserMapper;
import com.zjcode.cdcer.mapper.ZjcodeSysRegionMapper;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.service.SysUserService;
import com.zjcode.cdcer.service.TkmSysOrgService;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @ClassName:TkmSysOrgServiceImpl
 * @功能：
 * @author：wlei
 * @日期：2022/8/5-04:02
 **/
@Service
public class TkmSysOrgServiceImpl implements TkmSysOrgService, BaseService {

    @Autowired
    private TkmSysOrgMapper sysOrgMapper;
    @Autowired
    private TkmSysUserMapper sysUserMapper;
    @Autowired
    private ZjcodeSysRegionMapper zjcodeSysRegionMapper;

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public List<LinkedHashMap<String, Object>> listAll(PageData pageData) {
        return sysOrgMapper.listAllData(pageData);
    }

    @Override
    public List<TkmSysOrg> getAllOrgs() {
        return sysOrgMapper.getAllOrgs();
    }

    @Override
    public Map<Long,TkmSysOrg> getOrgInfoMap(){
        return sysOrgMapper.getAllOrgs().stream().collect(Collectors.toMap(TkmSysOrg::getId, org -> org));
    }

    @Override
    public Map<String, Object> listAllData(PageData pageData) {
        String userId = (String) pageData.get("user");
        TkmSysUser userInfo = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
        TkmSysOrg orgInfo = sysOrgMapper.selectByPrimaryKey(userInfo.getOrgId());
        pageData.put("ancestors", orgInfo.getAncestors());
        // 2023-11-28更新，如果登录用户属于筛查机构，那么只能看到自己机构的数据
        if (orgInfo.getOrgType().equals("org") && orgInfo.getExtFlag().equals("2")) {
            pageData.put("orgName", orgInfo.getOrgName());
        }
//        String orgId = sysUserService.findOrgByUserId(userId);
        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> list = sysOrgMapper.listAllData(pageData);
        // 展示绑定村
        if (!CollectionUtils.isEmpty(list)) {
            List<Object> orgIds = list.stream().map(map -> map.get("id")).collect(Collectors.toList());
            // orgVillages存在null的可能
            List<SysOrgVillage> orgVillages=sysOrgMapper.getOrgVillagesByOrgIds(orgIds);
            if (!CollectionUtils.isEmpty(orgVillages)) {
                List<String> villageCodes = orgVillages.stream().map(SysOrgVillage::getVillageCode).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                List<CityEntity> villages = sequenceService.getVillagesByCodes(villageCodes);
                orgVillages.forEach(item->{
                    villages.forEach(each->{
                        if (Objects.equals(each.getCode(),item.getVillageCode())) {
                            item.setVillageName(each.getName());
                        }
                    });
                });
                Map<String, List<SysOrgVillage>> orgVillageMaps = orgVillages.stream().collect(Collectors.groupingBy(SysOrgVillage::getOrgId));
                list.forEach(item->{
                    List<SysOrgVillage> infos = orgVillageMaps.get(item.get("id").toString());
                    String bindVillages = "";
                    if (!CollectionUtils.isEmpty(infos)) {
                        List<String> villageNames = infos.stream().map(SysOrgVillage::getVillageName).collect(Collectors.toList());
                        bindVillages = String.join("，",villageNames);
                    }
                    item.put("bindVillages",bindVillages);
                });
            }

        }
        return PaginationBuilder.buildResult(list,
                                             page.getTotal(),
                                             mPage.getCurrentPage(),
                                             mPage.getPageSize());
    }


    @Override
    public LinkedHashMap<String, Object> getAllProvince() {
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        List<LinkedHashMap<String, Object>> resultList = zjcodeSysRegionMapper.selectAllProvince();
        resultMap.put("list", resultList);
        return resultMap;
    }

    @Override
    public Map<String, Object> getAllProvinceCity(PageData pageData) {
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        String user = (String) pageData.get("user");

        // 父级机构的区域编码
        String parentReginCode = "";
        if (user != null) {
            TkmSysUser sysUser = sysUserMapper.selectByPrimaryKey(Long.parseLong(user));
            Long orgId = sysUser.getOrgId();
            TkmSysOrg org = sysOrgMapper.selectByPrimaryKey(orgId);
            String ancestors = org.getAncestors();
            String regionAncestors = org.getRegionAncestors();
            // 如果是县级疾控中心,则需要取出区域编码组中的第二位
            if (org
                .getOrgType()
                .equals("district")) {
                if (regionAncestors != null && regionAncestors.contains(",")) {
                    String[] split = regionAncestors.split(",");
                    parentReginCode = split[split.length - 2 > 0 ? split.length - 2 : 0];
                }
            } else {
                if (regionAncestors != null && regionAncestors.contains(",")) {
                    String[] split = regionAncestors.split(",");
                    parentReginCode = split[split.length - 1];
                }
            }


        }

        List<LinkedHashMap<String, Object>> allCities = zjcodeSysRegionMapper.getAllCities(pageData);
        if (!StringUtils.isEmpty(parentReginCode)) {
            // 执行数据过滤,如果是地市级别的机构，则只显示该机构下的数据,默认指挥有一条数据
            String finalParentReginCode = parentReginCode;
            allCities.removeIf(each -> {
                String regionCode = (String) each.get("id");
                return !regionCode.equals(finalParentReginCode);
            });
        }
        if (!CollectionUtils.isEmpty(allCities)) {
            resultMap.put("list", allCities);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDistrictAndStreet(PageData pageData) {
        //所有数据集合
        List<LinkedHashMap<String, Object>> zjcodeSysRegions = new ArrayList<>();
        //得到区数据
        List<LinkedHashMap<String, Object>> districts = zjcodeSysRegionMapper.getAllDistricts(
            pageData);
        List<String> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(districts)) {
            districts
                .parallelStream()
                .parallel()
                .forEach(region -> {
                    list.add(region
                                 .get("key")
                                 .toString());
                });
            zjcodeSysRegions.addAll(districts);
        }
        //拿街道等数据
        if (!CollectionUtils.isEmpty(list)) {
            List<LinkedHashMap<String, Object>> streets = zjcodeSysRegionMapper.getAllStreets(list);
            zjcodeSysRegions.addAll(streets);
        }
        LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        List<LinkedHashMap<String, Object>> sysRegions = buildTree(zjcodeSysRegions,
                                                                   (pageData.get("parentRegionCode")).toString());
        if (!CollectionUtils.isEmpty(sysRegions)) {
            resultMap.put("list", sysRegions);
        }
        return resultMap;
    }

    @Override
    public List<LinkedHashMap<String, Object>> exportOrgData(PageData pageData) {
        String userId = (String) pageData.get("user");
        TkmSysUser userInfo = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
        TkmSysOrg orgInfo = sysOrgMapper.selectByPrimaryKey(userInfo.getOrgId());
        pageData.put("ancestors", orgInfo.getAncestors());
        //返回数据集合
        List<LinkedHashMap<String, Object>> objects = new ArrayList<>();
        //查询导出的机构数据
        List<LinkedHashMap<String, Object>> maps = sysOrgMapper.exportOrgData(pageData);
        //适配导出代码
        maps
            .stream()
            .forEach(map -> {
                LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
                Object orgName = map.get("org_name");
                Object provinceName = map.get("province_name");
                Object cityName = map.get("city_name");
                Object regionName = map.get("region_name");
                Object regionCode = map.get("region_code");
                Object address = map.get("address");
                Object createTime = map.get("create_time");

                linkedHashMap.put("org_name", Objects.nonNull(orgName) ? orgName : "");
                linkedHashMap.put("province_name",
                                  Objects.nonNull(provinceName) ? provinceName : "");
                linkedHashMap.put("city_name", Objects.nonNull(cityName) ? cityName : "");
                linkedHashMap.put("region_name", Objects.nonNull(regionName) ? regionName : "");
                linkedHashMap.put("region_code", Objects.nonNull(regionCode) ? regionCode : "");
                linkedHashMap.put("address", Objects.nonNull(address) ? address : "");
                linkedHashMap.put("create_time",
                                  Objects.nonNull(createTime) ? new SimpleDateFormat(
                                      "yyyy-MM-dd HH:mm:ss").format(createTime) : "");
                objects.add(linkedHashMap);
            });
        return objects;
    }

    @Override
    public String getRegionCode(String orgId) {
        return sysOrgMapper.getRegionCode(orgId);
    }

    @Override
    public String getExFlag2(String orgId) {
        return sysOrgMapper.getExFlag2(orgId);
    }

    @Override
    public JsonObj saveBindList(PageData pageData) {
        // 机构主键id
        String id = (String)pageData.get("id");
        Object codeStrs = pageData.get("villageCodes");
        if (codeStrs==null) {
            return JsonObj.error("请先勾选需要绑定的村");
        }
        // 筛查年度的保存
        TkmSysOrg org = sysOrgMapper.selectByPrimaryKey(Long.valueOf(id));
        String screeningYear = org.getScreeningYear();
        // 当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        if (StringUtils.isEmpty(screeningYear)) {
            screeningYear = String.valueOf(year);
            org.setScreeningYear(screeningYear);
            sysOrgMapper.updateByPrimaryKeySelective(org);
        }else{
            if (!screeningYear.contains(String.valueOf(year))) {
                screeningYear += "，"+year;
                org.setScreeningYear(screeningYear);
                sysOrgMapper.updateByPrimaryKeySelective(org);
            }
        }
        // 得到勾选的村编号列表
        List<String> codes = Arrays.asList(String.valueOf(codeStrs).split("\\|"));
        // 过滤非村code的集合数据
        codes = codes.stream().filter(item -> item.length() > 11).collect(Collectors.toList());
        List<SysOrgVillage> orgVillages=new ArrayList<>();
        codes.forEach(each->{
            SysOrgVillage sysOrgVillage=new SysOrgVillage();
            sysOrgVillage.setId(get32UUID());
            sysOrgVillage.setOrgId(id);
            sysOrgVillage.setVillageCode(each);
            orgVillages.add(sysOrgVillage);
        });
        // 先删除该机构关联表
        sysOrgMapper.delOrgVillageByOrgId(id);
        // 新增机构 - 绑定村 关联表
        sysOrgMapper.addBatchOrgVillage(orgVillages);
        return JsonObj.success("绑定村成功");
    }

    @Override
    public JsonObj echoBindCodes(PageData pageData) {
        // 机构主键id
        String id = (String)pageData.get("id");
        List<String> villageCodes=sysOrgMapper.getVillageCodesByOrgId(id);
        Map<String, Object> data = new HashMap<>();
        data.put("codes", villageCodes);
        return JsonObj.success(data);
    }

    @Override
    public List<String> getVillageCodesByOrgId(String orgId) {
        return sysOrgMapper.getVillageCodesByOrgId(orgId);
    }

    @Override
    public String getOrgIdByVillageCode(String villageCode,List<String> orgIds) {
        return sysOrgMapper.getOrgIdByVillageCode(villageCode,orgIds);
    }

    @Override
    public List<String> getVillageCodesByOrgIds(List<String> orgIds) {
        return sysOrgMapper.getVillageCodesByOrgIds(orgIds);
    }

    @Override
    public JsonObj lockOrg(String id) {
        int count = sysOrgMapper.updateByPrimaryKeySelective(new TkmSysOrg(){{
            setId(Long.valueOf(id));setLocked("2");
        }});
        if (count > 0) {
            return JsonObj.success("锁定成功");
        }else{
            return JsonObj.error("锁定失败");
        }
    }

    @Override
    public JsonObj unlock(String id) {
        int count = sysOrgMapper.updateByPrimaryKeySelective(new TkmSysOrg(){{
            setId(Long.valueOf(id));setLocked("1");
        }});
        if (count > 0) {
            return JsonObj.success("解锁成功");
        }else{
            return JsonObj.error("解锁失败");
        }
    }

    @Override
    public JsonObj setAccount(PageData pageData) {
        int count = sysOrgMapper.setAccountAndPassword(pageData);
        if (count > 0) {
            return JsonObj.success("操作成功");
        }
        return JsonObj.error("操作失败");
    }


    private List<LinkedHashMap<String, Object>> buildTree(List<LinkedHashMap<String, Object>> regionList,
                                                          String parentRegionCode) {
        List<LinkedHashMap<String, Object>> rootList = new ArrayList<>();
        regionList
            .stream()
            .forEach(region -> {
                if (region
                    .get("parentId")
                    .equals(parentRegionCode)) {
                    rootList.add(region);
                }
            });
        regionList
            .stream()
            .forEach(region -> {
                childrenMenu(regionList, region, parentRegionCode);
            });
        return rootList;
    }

    private LinkedHashMap<String, Object> childrenMenu(List<LinkedHashMap<String, Object>> regionList,
                                                       LinkedHashMap<String, Object> region,
                                                       String parentRegionCode) {
        List<LinkedHashMap<String, Object>> children = new ArrayList<>();
        regionList
            .stream()
            .forEach(zjcodeSysRegion -> {
                if (zjcodeSysRegion
                    .get("parentId")
                    .equals(region.get("key"))) {
                    children.add(childrenMenu(regionList, zjcodeSysRegion, parentRegionCode));
                }
            });
        region.put("children", children);
        return region;
    }
}
